package com.sylar.lelepub;

import java.util.ArrayList;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.sylar.lelepub.adapter.DetailPubAdapter;
import com.sylar.lelepub.adapter.DetailPubCommAdapter;
import com.sylar.lelepub.widget.ScrollLayout;
import com.sylar.lelepub.widget.ScrollLayout.ScrollLayoutChange;
import com.sylar.lelepub.widget.XListView;

public class DetailPubActivity extends MapActivity implements OnClickListener,ScrollLayoutChange {
	private Button btn_pub_comm;
	private Button btn_pub_map;
	private Button btn_pub_type;
	private Button btn_title_right;
	private Button btn_title_left;

	private ScrollLayout pub_scrolllayout;
	private View parent;
	private XListView pubtype_listView,pubcomm_listView;
	private String longitude = "";
	private String latitude = "";
	
	private String mStrKey = "B7DCE5A8C3B0448ECE5D4FF2D042183C7A2F8DF8";
	private MyLocationOverlay myloc;
	private BMapManager mapManager;
	private MapView mMapView = null; // 地图View
	
	private ImageButton planDetial;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_detailpub);

		TextView tv_title_name = (TextView) findViewById(R.id.tv_title_name);
		tv_title_name.setText("北京银马酒店");

		btn_title_right = (Button) findViewById(R.id.btn_title_right);
		btn_title_right.setVisibility(View.VISIBLE);
		btn_title_right.setText("收藏");
		btn_title_right.setOnClickListener(this);

		btn_title_left = (Button) findViewById(R.id.btn_title_left);
		btn_title_left.setVisibility(View.VISIBLE);
		btn_title_left.setOnClickListener(this);

		btn_pub_comm = (Button) findViewById(R.id.btn_pub_comm);
		btn_pub_map = (Button) findViewById(R.id.btn_pub_map);
		btn_pub_type = (Button) findViewById(R.id.btn_pub_type);

		btn_pub_comm.setOnClickListener(this);
		btn_pub_map.setOnClickListener(this);
		btn_pub_type.setOnClickListener(this);
		
		
		TextView tv_pub_address = (TextView) findViewById(R.id.tv_pub_address);
		TextView tv_pub_telno = (TextView) findViewById(R.id.tv_pub_telno);
		
		ImageView img_pub_cover = (ImageView) findViewById(R.id.img_pub_cover);
		
		View layout_pub_type = getLayoutInflater().inflate(R.layout.layout_pub_type, null);
		View layout_pub_comm = getLayoutInflater().inflate(R.layout.layout_pub_comm, null);
		
		View layout_pub_map = getLayoutInflater().inflate(R.layout.routeplan, null);
		parent = layout_pub_map.findViewById(R.id.parent);
		
		mapManager = new BMapManager(this);
		// init方法的第一个参数需填入申请的APIKey
		mapManager.init(mStrKey, new LeLePubApplication.MyGeneralListener());
		mapManager.start();
//		planDetial.setOnClickListener(this);
		super.initMapActivity(mapManager);

		mMapView = (MapView) layout_pub_map.findViewById(R.id.bmapView);
		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);
		myloc = new MyLocationOverlay(this, mMapView);
		myloc.enableCompass(); // 启用指南针
		initmap();
		
		
		TextView tv_sleep_pub_start_time = (TextView) layout_pub_type.findViewById(R.id.tv_sleep_pub_start_time);
		TextView tv_sleep_pub_start_week = (TextView) layout_pub_type.findViewById(R.id.tv_sleep_pub_start_week);
		TextView tv_sleep_pub_end_time = (TextView) layout_pub_type.findViewById(R.id.tv_sleep_pub_end_time);
		TextView tv_sleep_pub_end_week = (TextView) layout_pub_type.findViewById(R.id.tv_sleep_pub_end_week);
		TextView tv_sleep_pub_sleep_round = (TextView) layout_pub_type.findViewById(R.id.tv_sleep_pub_sleep_round);
		
		
		pubcomm_listView = (XListView) layout_pub_comm.findViewById(R.id.pubcomm_listView);
		pubtype_listView = (XListView) layout_pub_type.findViewById(R.id.pubtype_listView);
		
		List<String> detailPages = new ArrayList<String>();
		for(int i=0;i<20;i++){
			detailPages.add(""+i);
		}
		
		
		DetailPubAdapter detailPubAdapter = new DetailPubAdapter(getApplicationContext());
		detailPubAdapter.setListPageItems(detailPages);
		pubtype_listView.setAdapter(detailPubAdapter);
		
		DetailPubCommAdapter detailPubCommAdapter = new DetailPubCommAdapter(getApplicationContext());
		detailPubCommAdapter.setListPageItems(detailPages);
		pubcomm_listView.setAdapter(detailPubCommAdapter);
		
		pub_scrolllayout = (ScrollLayout) findViewById(R.id.pub_scrolllayout);
		pub_scrolllayout.setOnViewChangeListener(this);
		
		pub_scrolllayout.addView(layout_pub_type);
		pub_scrolllayout.addView(layout_pub_comm);
		pub_scrolllayout.addView(layout_pub_map);
		
		pub_scrolllayout.snapToScreen(0);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_title_left:
			finish();
			break;
		case R.id.btn_title_right:

			break;

		case R.id.btn_pub_comm:
			if (pub_scrolllayout != null)
				pub_scrolllayout.snapToScreen(1);
			break;
		case R.id.btn_pub_map:
			if (pub_scrolllayout != null)
				pub_scrolllayout.snapToScreen(2);
			break;
		case R.id.btn_pub_type:
			if (pub_scrolllayout != null)
				pub_scrolllayout.snapToScreen(0);
			break;
		}
		
	}
	
	void toPubType(){
		if(btn_pub_type!=null){
			btn_pub_type.setSelected(true);
			btn_pub_type.setTextColor(Color.parseColor("#FFFFFF"));
		}
		if(btn_pub_comm!=null){
			btn_pub_comm.setTextColor(Color.parseColor("#b1b1b1"));
			btn_pub_comm.setSelected(false);
		}
			
		if(btn_pub_map!=null){
			btn_pub_map.setTextColor(Color.parseColor("#b1b1b1"));
			btn_pub_map.setSelected(false);
		}
			
	}

	void toPubComm(){
		if(btn_pub_type!=null){
			btn_pub_type.setSelected(false);
			btn_pub_type.setTextColor(Color.parseColor("#b1b1b1"));
		}
		if(btn_pub_comm!=null){
			btn_pub_comm.setTextColor(Color.parseColor("#FFFFFF"));
			btn_pub_comm.setSelected(true);
		}
			
		if(btn_pub_map!=null){
			btn_pub_map.setTextColor(Color.parseColor("#b1b1b1"));
			btn_pub_map.setSelected(false);
		}
	}
	void toPubMap(){
		if(btn_pub_type!=null){
			btn_pub_type.setSelected(false);
			btn_pub_type.setTextColor(Color.parseColor("#b1b1b1"));
		}
		if(btn_pub_comm!=null){
			btn_pub_comm.setTextColor(Color.parseColor("#b1b1b1"));
			btn_pub_comm.setSelected(false);
		}
			
		if(btn_pub_map!=null){
			btn_pub_map.setTextColor(Color.parseColor("#FFFFFF"));
			btn_pub_map.setSelected(true);
		}
	}

	@Override
	public void onViewChange(int curScreen) {
		if(curScreen == 0 ){
			toPubType();
		}else if(curScreen == 1 ){
			toPubComm();
		}else if(curScreen == 2 ){
			toPubMap();
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	private int lat, lon;// 经纬度
	private LocationListener mLocationListener = null;// create时注册此listener，Destroy时需要Remove
	private MKSearch mSearch = null;
	
	private void initmap() {

		if (longitude == null || latitude == null
				|| longitude.equals("")
				|| longitude.equals("null")
				|| latitude.equals("")
				|| latitude.equals("null")) {
			myloc.enableMyLocation(); // 启用定位
			mMapView.getOverlays().add(myloc);
		} else {
			Drawable marker = getResources().getDrawable(R.drawable.iconmarka); // 得到需要标在地图上的资源
			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
					marker.getIntrinsicHeight());
			mMapView.getOverlays().add(new MyOverlay(marker));
		}

		mSearch = new MKSearch();
		mSearch.setTransitPolicy(MKSearch.ECAR_TIME_FIRST);
		mLocationListener = new LocationListener() {
			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					lat = (int) (location.getLatitude() * 1E6);
					lon = (int) (location.getLongitude() * 1E6);
					GeoPoint point = null;
					MapController mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
					if (longitude != null
							&& latitude != null
							&& !longitude.equals("null")
							&& !latitude.equals("null")
							&& !longitude.equals("")
							&& !latitude.equals("")) {
						point = new GeoPoint(
								(int) (Double.valueOf(latitude) * 1E6),
								(int) (Double.valueOf(longitude) * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度(度
						mMapView.getController().animateTo(point);
						mMapController.setCenter(point); // 设置地图中心点
					}
					mMapController = mMapView.getController();
					// 设置地图的中心
					mMapController.setZoom(12); // 设置地图zoom级别

				}
			}
		};
		mSearch.init(mapManager, new MKSearchListener() {

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(DetailPubActivity.this,
							"未找到搜索内容", Toast.LENGTH_SHORT).show();
					
					return;
				}
				
				RouteOverlay routeOverlay = new RouteOverlay(
						DetailPubActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);

			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(DetailPubActivity.this,
							"未找到搜索内容", Toast.LENGTH_SHORT).show();
					return;
				}
				TransitOverlay routeOverlay = new TransitOverlay(
						DetailPubActivity.this, mMapView);
				// 此处仅展示一个方案
				// 获取公交线路的详细信息
				routeOverlay.setData(res.getPlan(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(DetailPubActivity.this,
							"未找到搜索内容", Toast.LENGTH_SHORT).show();
					return;
				}
				// 加载步行路线的详细结果
				RouteOverlay routeOverlay = new RouteOverlay(
						DetailPubActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.invalidate();
				mMapView.getController().animateTo(res.getStart().pt);

			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
			}
		});
	}
	
	/**
	 * 显示当前位置在那里
	 * @author Administrator
	 *
	 */
	class MyOverlay extends ItemizedOverlay<OverlayItem> {
		Drawable marker;
		public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();

		public MyOverlay(Drawable marker) {
			super(boundCenterBottom(marker));
			GeoPoint geoPoint = new GeoPoint(
					(int) (Double.valueOf(latitude) * 1E6),
					(int) (Double.valueOf(longitude) * 1E6));
			mGeoList.add(new OverlayItem(geoPoint, "在这里",
					"point1"));
			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// 在天安门的位置绘制一个String
			// Point point = mMapView.getProjection().toPixels(geoPoint, null);
			// paint.setColor(Color.RED);
			// paint.setTextSize(16);
			// canvas.drawText("店铺位置", point.x, point.y, paint);
			// super.draw(canvas, mapView, shadow);
			// //调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			// Bitmap bitmap=BitmapFactory.decodeResource(getResources(),
			// R.drawable.iconmarka);
			// canvas.drawBitmap(bitmap, point.x, point.y, paint);
			// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
			Projection projection = mapView.getProjection();
			for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
				OverlayItem overLayItem = getItem(index); // 得到给定索引的item
				String shopTitle = overLayItem.getTitle();
				// 把经纬度变换到相对于MapView左上角的屏幕像素坐标
				Point point = projection.toPixels(overLayItem.getPoint(), null);
				// 可在此处添加您的绘制代码
				Paint paintText = new Paint();
				paintText.setColor(Color.BLUE);
				paintText.setTextSize(25);
				canvas.drawText(shopTitle, point.x + 10, point.y, paintText); // 绘制文本
			}

			super.draw(canvas, mapView, shadow);
			// 调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			boundCenterBottom(marker);

		}

		@Override
		protected OverlayItem createItem(int arg0) {
			// TODO Auto-generated method stub
			return mGeoList.get(arg0);
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return mGeoList.size();
		}
	}
	
	@Override
	protected void onDestroy() {
		if (mapManager != null) {
			// 程序退出前需调用此方法
			mapManager.destroy();
			mapManager = null;
		}
		super.onDestroy();
	}
}
